﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using Biciq.Logica;
using Biciq.Datos;

namespace Biciq.Logica
{
    public class EvaluacionMemberShipProvider : MembershipProvider
    {
        private Boolean requiresQuestionAndAnswer;
        private Boolean enablePasswordRetrieval;
        private Boolean enablePasswordReset;
        private Boolean requiresUniqueEmail;
        private int minRequiredPasswordLength;
        private int minRequiredNonalphanumericCharacters;
        private MembershipCreateStatus state { get; set; }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            requiresQuestionAndAnswer = Convert.ToBoolean(config["requiresQuestionAndAnswer"]);
            enablePasswordRetrieval = Convert.ToBoolean(config["enablePasswordRetrieval"]);
            enablePasswordReset = Convert.ToBoolean(config["enablePasswordReset"]);
            requiresUniqueEmail = Convert.ToBoolean(config["requiresUniqueEmail"]);
            minRequiredPasswordLength = Convert.ToInt32(config["minRequiredPasswordLength"]);
            minRequiredNonalphanumericCharacters = Convert.ToInt32(config["minRequiredNonalphanumericCharacters"]);


        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            using (SecurityService securityService = new SecurityService())
            {
                Result result = securityService.changePassword(username, oldPassword, newPassword);
                return result.estado;
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (ValidateUser(username.ToUpper(), password) && GetUserNameByEmail(email) == "")
            {

                status = MembershipCreateStatus.Success;
                //SecurityService securityService = new SecurityService();
                //Usuario user = new usuario();
                //user.creationDate = DateTime.Now;
                //user.email = email;

                //if (passwordAnswer == "Administrador")
                //{
                //    user.password = CommonService.encript(username);
                //    user.Profile_Id = securityService.getProfileCreateAdministrator().Id;
                //    user.isFirstTime = true;
                //}
                //else
                //{
                //    user.password = CommonService.encript(password);
                //    user.Profile_Id = securityService.getProfileCreateUser().Id;
                //    user.isFirstTime = false;
                //}


                //user.userName = username.ToUpper();



                //Result result = securityService.createUser(user);
                //if (!result.state)
                //{
                //    status = MembershipCreateStatus.ProviderError;
                //}
                //else
                //{
                //    result = enviarCorreo(user);

                //}


            }
            else
            {
                status = state;
            }
            return GetUser(username, true);
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { return enablePasswordReset; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return enablePasswordRetrieval; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return new MembershipUser("EvaluacionMemberShipProvider", username,
                null,
                "",
                "",
                "",
                true,
                false,
                new DateTime(),
                new DateTime(),
                new DateTime(),
                new DateTime(),
                new DateTime());
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return minRequiredNonalphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return minRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            using (BiciqContexto context = new BiciqContexto())
            {
                var user = context.Usuarios.Where(u => u.nombreUsuario == username).FirstOrDefault();
                if (user == null)
                {
                    state = MembershipCreateStatus.InvalidUserName;
                    return false;
                }
                if (password.Length < MinRequiredPasswordLength)
                {
                    state = MembershipCreateStatus.InvalidPassword;
                    return false;
                }
                if (Comun.encript(password)!=user.clave)
                {
                    state = MembershipCreateStatus.InvalidPassword;
                    return false;
                }
                return true;


            }
        }
       
    }
}
